package com.lyz;

import com.github.benmanes.caffeine.cache.AsyncCache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class AsyncCaffeine {
    public static void main(String[] args) {
        // 创建异步缓存
        AsyncCache<String, String> cache = Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .maximumSize(100)
                .buildAsync();

        // 异步加载缓存项
        CompletableFuture<String> futureValue = cache.get("key1", key -> {
            // 模拟耗时操作，如从数据库中加载数据
            return "asyncValue";
        });

        // 获取缓存项
        String value = null;
        try {
            value = futureValue.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("取出异步缓存值：" + value);
    }

}
